#include "loginwindow.h"
#include "ui_loginwindow.h"
#include <QCryptographicHash>
#include <QMessageBox>
#include "registerwindow.h"
#include <QJsonArray>
#include <QProgressDialog>
#include <QCoreApplication>
#include <QThread>
#include <QTimer>

LoginWindow::LoginWindow(TcpClient* client,QWidget *parent)
    : QDialog(parent),ui(new Ui::LoginWindow),m_tcpClient(client),m_isConnectedToServer(false)
{
    ui->setupUi(this);

    this->setWindowTitle("应用名称");

    ui->LoginpushButton->setEnabled(false);
    ui->RegisterpushButton->setEnabled(false);

    // 创建网络客户端实例并连接到服务器
    // m_tcpClient = new TcpClient(this);使用传入的client就行
    // m_tcpClient->connectToServer("127.0.0.1", 8888);
    //把连接任务交到登陆按钮点击后


    // 连接 TcpClient 的信号到我们自己的槽
    connect(m_tcpClient, &TcpClient::serverResponse, this, &LoginWindow::onServerResponse);
    connect(m_tcpClient,&TcpClient::myConnectedToServer,this,&LoginWindow::onMyConnectedToServer);
    connect(m_tcpClient,&TcpClient::myDisconnectedFromServer,this,&LoginWindow::onMyDisconnectedFromServer);
    connect(m_tcpClient,&TcpClient::myConnectErrorOccurred,this,&LoginWindow::onMyConnectErrorOccurred);

    // Qt 会自动将 ui->buttonBox 的 accepted() 信号连接到 on_buttonBox_accepted() 槽

    m_connectionTimer = new QTimer(this);
    // 设置为单次触发模式
    m_connectionTimer->setSingleShot(true);

    // --- 将定时器的 timeout() 信号，连接到一个新的超时处理槽 ---
    connect(m_connectionTimer, &QTimer::timeout, this,[this]()
    {
        // 定时器触发了，说明连接超时
        qDebug() << "Connection attempt timed out after 3 seconds.";

        // 1. 手动中止底层的连接尝试
        m_tcpClient->abortConnection(); // 假设 TcpClient 有这个函数

        // 2. 弹窗提示用户
        QMessageBox::critical(this, "连接超时", "无法在规定时间内连接到服务器，请检查：\n"
                                                "1. 服务器 IP 地址是否正确。\n"
                                                "2. 网络是否通畅，或防火墙是否拦截。");

        // 3. 恢复 UI 状态
        ui->connectServerpushButton->setEnabled(true);
        m_isConnectedToServer = false;
        ui->LoginpushButton->setEnabled(false);
        ui->RegisterpushButton->setEnabled(false);
    });

}

LoginWindow::~LoginWindow()
{
    delete ui;
}

//当用户点击登陆按钮后
void LoginWindow::on_LoginpushButton_clicked()
{
    // --- 1. 获取输入信息 ---
    QString username = ui->usernameLineEdit->text();
    QString password = ui->passwordLineEdit->text();
    QString serverIp = ui->IPlineEdit->text().trimmed();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "用户名和密码不能为空！");
        m_tcpClient->disconnectFromServer();
        return;
    }

    // b. 构建并发送登录请求
    qDebug() << "Connection successful! Sending login request...";
    QJsonObject loginRequest;
    loginRequest["type"] = "login_request";
    loginRequest["username"] = username;
    QByteArray passwordHash = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Md5);
    loginRequest["password"] = QString(passwordHash.toHex());

    m_tcpClient->sendJson(loginRequest);
    return ;
}

// 处理从服务器收到的所有响应
void LoginWindow::onServerResponse(const QJsonObject &response)
{
    QString type = response["type"].toString();

    if (type == "login_response")
    {
        bool success = response["success"].toBool();
        if (success)
        {
            // 登录成功！
            // 提取 user_id 和 username 作为 userInfo
            QJsonObject userInfo;
            userInfo["user_id"] = response["user_id"];
            userInfo["username"] = response["username"];

            QJsonArray friends = response["friends"].toArray();
            this->close();
            emit loginSuccess(userInfo, friends); // 发射带数据的信号
        } else
        {
            // 登录失败
            QString error = response["error_message"].toString();
            QMessageBox::critical(this, "登录失败", error);
            ui->LoginpushButton->setEnabled(true);
            ui->RegisterpushButton->setEnabled(true);
        }
    }
    // 以后可以在这里添加 else if 来处理 register_response 等
}
void LoginWindow::on_RegisterpushButton_clicked()
{
    // 创建并以模态方式显示注册窗口
    // 模态意味着在关闭这个窗口前，无法与登录窗口交互
    // 将 tcpClient 指针也传递给注册窗口
    RegisterWindow regWin(m_tcpClient,this); // 将登录窗口作为父窗口
    regWin.exec();
}

void LoginWindow::on_connectServerpushButton_clicked()
{
    QString serverIp = ui->IPlineEdit->text().trimmed();
    if(serverIp.isEmpty() == true)
    {
        QMessageBox::warning(this, "错误", "服务器地址不能为空！");
        return ;
    }


    if (m_isConnectedToServer)
    {
        // 如果已连接，则此按钮的功能是“断开”,使用新的IP进行连接
        m_tcpClient->disconnectFromServer();
        m_isConnectedToServer = false;
        QThread::msleep(200);
    }
    // 如果未连接，则此按钮的功能是“连接”
    ui->connectServerpushButton->setEnabled(false);
    m_connectionTimer->start(3000); // 设置超时时间为 3000 毫秒 (3秒)

    if (serverIp.isEmpty())
    {
        QMessageBox::warning(this, "错误", "服务器地址不能为空！");
        return;
    }

    m_tcpClient->connectToServer(serverIp, 8888);

    return ;
}

void LoginWindow::onMyConnectedToServer()
{
    m_connectionTimer->stop();
    m_isConnectedToServer = true;
    ui->LoginpushButton->setEnabled(true);
    ui->RegisterpushButton->setEnabled(true);
    ui->connectServerpushButton->setEnabled(true);

    return ;
}

void LoginWindow::onMyDisconnectedFromServer()
{
    m_isConnectedToServer = false;
    ui->LoginpushButton->setEnabled(false);
    ui->RegisterpushButton->setEnabled(false);
    ui->connectServerpushButton->setEnabled(true);

    return ;
}

void LoginWindow::onMyConnectErrorOccurred(QString message)
{
    // --- 关键修改：如果定时器还在运行，也停止它 ---
    if (m_connectionTimer->isActive()) {
        m_connectionTimer->stop();
    }

    m_isConnectedToServer = false;
    ui->LoginpushButton->setEnabled(false);
    ui->RegisterpushButton->setEnabled(false);
    ui->connectServerpushButton->setEnabled(true);

    QMessageBox::critical(this, "连接失败", message);

    return ;
}
